package goodroommate.dao.impl;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.LinkedList;
import goodroommate.dal.DatabaseSession;
import goodroommate.dao.INewsDao;
import goodroommate.domain.News;
import goodroommate.exception.DatabaseException;

public class NewsDao implements INewsDao {

	@Override
	public LinkedList<News> getNews(DatabaseSession dbs) throws DatabaseException {
		
		String sql="SELECT * FROM news ORDER BY Time DESC LIMIT 0,5 ";
		LinkedList<News>rst=new LinkedList<News>();
		try{
			ResultSet rs=dbs.executeQuery(sql);
			while(rs.next()){
				News news=new News();
				news.setNewsid(rs.getInt("NewsID"));
				news.setSubject(rs.getString("Subject"));
				news.setContent(rs.getString("Content"));
				news.setTime(rs.getTimestamp("Time"));
				rst.add(news);
			}
			return rst;
		}catch(SQLException e){
			e.printStackTrace();
			throw new DatabaseException(e);
		}
	}

	@Override
	public LinkedList<News> getAllNews(DatabaseSession dbs) throws DatabaseException {
		
		String sql="SELECT * FROM news ORDER BY Time DESC";
		LinkedList<News>rst=new LinkedList<News>();
		try{
			ResultSet rs=dbs.executeQuery(sql);
			while(rs.next()){
				News news=new News();
				news.setNewsid(rs.getInt("NewsID"));
				news.setSubject(rs.getString("Subject"));
				news.setContent(rs.getString("Content"));
				news.setTime(rs.getTimestamp("Time"));
				rst.add(news);
			}
			return rst;
		}catch(SQLException e){
			e.printStackTrace();
			throw new DatabaseException(e);
		}
	}
	@Override
	public News getNewsByID(DatabaseSession dbs, int newsid) throws DatabaseException {
		if(newsid==0)
			return null;
		String sql="SELECT * FROM news WHERE NewsID=?";
		try{
			ResultSet rs=dbs.executeQuery(sql, newsid);
			if(rs.next()){
				News news=new News();
				news.setNewsid(rs.getInt("NewsID"));
				news.setSubject(rs.getString("Subject"));
				news.setContent(rs.getString("Content"));
				news.setTime(rs.getTimestamp("Time"));	
				return news;
			}
			else
				return null;
		}catch(SQLException e){
			e.printStackTrace();
			throw new DatabaseException(e);
		}
		
	}

	@Override
	public boolean addNews(DatabaseSession dbs, News news) throws DatabaseException {
		
		String sql="INSERT INTO	 news (Subject,Content) VALUES (?,?)";
		try{
			dbs.executeUpdate(sql, news.getSubject(),news.getContent());
			return true;
		}catch(DatabaseException e){
			e.printStackTrace();
			throw new DatabaseException(e);
		}
		
	}
	
	

}
